How to generate execution logs with PHP

(Originally posted on my Portuguese blog at rberaldo.com.br)

Execution logs are very useful for “cataloging” the execution cycle of a program. Every action performed by the software is recorded in a file, along with the date and time of the occurrence.

Many programmers clutter the screen with echo and var_dump statements to discover what is happening in the code. This is not entirely wrong, but there are better alternatives. In fact, I’ve seen people forget to remove var_dump before deploying a system. The result: everyone can see the debug when accessing the site…

In this article, I will show you how to create a simple logging system using PHP.

How a Log File Should Be

A simple example of a log entry in a log file looks like this:

[2015-03-31 00:00:00] INFO: Executing action X...

Very straightforward, nothing special.

The log file is nothing more than a collection of entries, one per line, indicating the date and time when a specific event occurred.

In the example above, I included the log level, represented by the word “INFO.” In this case, it’s an Information log. There could be other levels, such as Warnings (WARNING) and errors (ERROR).

Function for Generating Logs

I will show you a simple function for creating logs.

Let’s consider the three types (referred to as levels) of logs I mentioned earlier in this article.

I’ll name the function logMsg. It accepts three parameters, but only the first one is mandatory.

The first parameter is the log message. The second is the log level (it can be info, which is the default value, warning, or error). The third parameter is the name of the file where the log will be written. By default, it will be written to the “main.log” file.

Let’s look at the code with accompanying comments.

function logMsg($msg, $level = 'info', $file = 'main.log') {
    // will hold the log level (INFO, WARNING or ERROR)
    $levelStr = '';

    // checks log level
    switch ($level) {
        case 'info':
            $levelStr = 'INFO';
            break;

        case 'warning':
            $levelStr = 'WARNING';
            break;

        case 'error':
            $levelStr = 'ERROR';
            break;
    }

    // current date and time
    $date = date('Y-m-d H:i:s');

    // formats the log message
    // 1o: current date
    // 2o: log level (INFO, WARNING or ERROR)
    // 3o: the log message itself
    // 4o: line break
    $msg = sprintf("[%s] [%s]: %s%s", $date, $levelStr, $msg, PHP_EOL);

    // writes the message to the log file
    // the FILE_APPEND appends the message to the end of the file
    file_put_contents($file, $msg, FILE_APPEND);
}

How to Use the Log Generation Function

To use the logMsg function we created, simply call it with at least the first parameter.

Here are some examples.

Generating an Information Log

To generate a simple information log, use the following example:

logMsg("Executing task X...");

This will generate the following line in the log file:

[2015-04-03 22:07:03] [INFO]: Executing task X...

Generating a Warning Log

To generate a warning log, use the following example:

logMsg("This is a warning... operation X may fail...", 'warning');

This will generate the following line in the log file:

[2015-04-03 22:07:03] [WARNING]: This is a warning... operation X may fail...

Generating an Error Log

To generate an error log, use the following example:

logMsg("This is an error. Operation X failed", 'error');

This will generate the following line in the log file:

[2015-04-03 22:07:03] [ERROR]: This is an error. Operation X failed

Why Didn’t I Use PHP’s error_log Function

PHP has the error_log function. You are free to use it if you prefer.

I chose not to use it because it does not allow me to use the additional settings I find useful, such as the log level. It is more focused on errors, as the name of the function suggests.

Be Cautious About the Amount of Logs

Logs are very useful, of course. But there is a cost to the server.

Each write operation to the log file consumes CPU time and makes your application a bit slower. It’s barely noticeable when there are only a few logs.

However, if you configure an excessive amount of log generation, you will see a drop in performance, especially if your system receives many simultaneous accesses. After all, disk writing is one of the most CPU-intensive tasks.

So, use logs cautiously. Generate logs only when truly necessary. Avoid creating useless logs. If you generate logs only for debugging during development, remember to remove them before deploying the application into production.

PSR-3 Logging Standard

The PHP-FIG group created, among other recommendations, PSR-3, which is a standardization recommendation for logging libraries.

If you already have knowledge of Object-Oriented Programming (OOP), I recommend studying PSR-3 and applying it to your projects. If you are not yet familiar with OOP, take your time. Use the function I showed in this post, and later, when you have mastered OOP, apply the concepts of PSR-3.

Related posts

4 Thoughts to “How to generate execution logs with PHP”

  1. wilterson garcia

    O que por exemplo geraria uma mensagem de Warning?

    1. Um Warning é uma situação que pode gerar um erro, mas que sua aplicação tem capacidade de contornar.

      Uma discussão sobre isso:
      http://stackoverflow.com/questions/2031163/when-to-use-log-level-warn-vs-error

      A RFC-5424 estabelece os 8 níveis de logs:
      http://tools.ietf.org/html/rfc5424

  2. Helder Pontes

    Amigo, onde este arquivo main.log ficará gravado?

    Helder Pontes

    1. Olá, Helder

      O main.log vai ficar no diretório onde o script foi requisitado.
      Porém eu recomendo sempre definir o local dele, passando o caminho completo por parâmetro.
      Assim os logs serão escritos sempre no mesmo arquivo, mesmo que o arquivo php que gerou o log esteja em outro diretório

Leave a Comment